package cn.yx.common.sentinel.handler;

import cn.yx.common.core.enums.SentinelExceptionEnum;
import cn.yx.common.core.exception.AppException;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>URL资源的流控异常，可以被此类捕捉到。如果是服务资源的流控规则，此类捕捉不到，可用yx-common-starter-web中的GlobalExceptionHandler处理</p>
 *
 * @author Wgsssmart
 */
@Configuration
@Slf4j
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) {
        // getRule返回资源、规则的详细信息
        log.error("BlockExceptionHandler rule: {}", e.getRule());
        SentinelExceptionEnum sentinelExceptionEnum = SentinelExceptionEnum.findByValue(e.getClass().getSimpleName());
        // 抛出异常，可在yx-common-starter-webmvc模块的GlobalExceptionHandler中捕捉处理
        throw new AppException(sentinelExceptionEnum.getMessage(), e);
    }
}
